package cn.gdpu.course.web.controller.admin;

import cn.gdpu.course.constant.Constant;
import cn.gdpu.course.dao.CourseTypeDao;
import cn.gdpu.course.dao.domain.CourseType;
import cn.gdpu.course.web.bean.PageBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Administrator on 2018/3/17.
 */

@Controller
@RequestMapping("/admin/courseType")
public class AdmCourseTypeController {

	@Resource
	private CourseTypeDao courseTypeDao;

	@RequestMapping(method = RequestMethod.GET)
	public String index(HttpServletRequest request, ModelMap model) {
		String username = (String) request.getSession().getAttribute(Constant.user_name);
		model.addAttribute("username", username);
		return "admin/course-type";
	}

	@ResponseBody
	@RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
	public PageBean<CourseType> list(ModelMap model, CourseType courseType) {
		List<CourseType> courseTypes = courseTypeDao.find(courseType);
		PageBean<CourseType> data = new PageBean<CourseType>();
		data.setData(courseTypes);
		return data;
	}

	@ResponseBody
	@RequestMapping(value = "/findById", method = {RequestMethod.GET, RequestMethod.POST})
	public CourseType findById(ModelMap model, CourseType courseType) {
		List<CourseType> courseTypes = courseTypeDao.find(courseType);
		if (CollectionUtils.isEmpty(courseTypes)) {
			return null;
		} else {
			return courseTypes.get(0);
		}
	}

	@ResponseBody
	@RequestMapping(value = "/save", method = {RequestMethod.GET, RequestMethod.POST})
	public int save(ModelMap model, CourseType courseType) {
		List<CourseType> courseTypes = courseTypeDao.find(courseType);
		if (!CollectionUtils.isEmpty(courseTypes)) {
			return -1;
		}
		return courseTypeDao.save(courseType) ? 1 : 0;
	}

	@ResponseBody
	@RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
	public int update(ModelMap model, CourseType courseType) {
		CourseType ct = new CourseType();
		ct.setTname(courseType.getTname());
		List<CourseType> courseTypes = courseTypeDao.find(ct);
		if (!CollectionUtils.isEmpty(courseTypes)) {
			if (courseType.getId() != courseTypes.get(0).getId()) {
				return -1;
			}
		}
		return courseTypeDao.update(courseType) ? 1 : 0;
	}

	@ResponseBody
	@RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
	public Boolean delete(ModelMap model, CourseType courseType) {
		return courseTypeDao.delete(courseType);
	}

}
